var getPixels = require("get-pixels");
var fs = require("fs");

module.exports.img2PixelStr = img2PixelStr;

/**
 *  config 参数 fileName, smallRate, finalWidth
 */
function img2PixelStr(config, callback) {
  const BIG_THRESHOLD = 900;
  const SMALL_THRESHOLD = 900;
  var SMALL_RATE = 1;
  var j = 0;
  var pixelsArr = [];
  var pixelsArrB = [];
  var pixelsArrS = [];
  var imgHeight, imgWidth;

  var testImgPath = "http://maxmon.top/images/wordPic/chuyin.jpg";
  const PIXEL_SRC_PATH = "/home/maxmon/img/pixelSrc/";

  // var config = {
  //   fileName: "./20170716030754����Ƥ����������.gif",
  //   finalWidth: 20
  // }

  // img2PixelStr(config, function (res) {
  //   console.log(res);
  // })

  var imgPath = config.fileName ? ((config.filePath || PIXEL_SRC_PATH) + config.fileName) : testImgPath;
  getPixels(imgPath, function (err, pixels) {
    if (err) {
      console.log("Bad image path", imgPath);
      callback("图片格式错");
      return
    }
    console.log(imgPath);
    console.log(pixels)
    console.log(pixels.shape)
    const colorFontsNum = pixels.shape[2];
    const colorPixelCount = pixels.data.length;
    while (j < colorPixelCount) {
      var pixelsColor = 0;
      for (var i = 0; i < 4; i++) {
        pixelsColor += pixels.data[j];
        j++;
      }
      pixelsArr.push(pixelsColor);
    }
    imgWidth = pixels.shape[0];
    imgHeight = pixels.shape[1];
    var smallRate = config.smallRate || SMALL_RATE;
    if (config.finalWidth) {
      // 把宽度缩小到10个字为止
      smallRate = imgWidth / config.finalWidth;
    }
    console.log(smallRate);
    // console.log(pixelsArr);
    var imgStr = "";
    heightCalculate(smallRate);
    var blackArrNum = 0;
    var arrNum = 0;
    var pixelsSum = 0;
    for (var y = 0; y < pixelsArrB.length; y++) {
      for (var x = 0; x < pixelsArrB[0].length; x++) {
        if (pixelsArrS[y][x] != undefined) {
          arrNum++;
          pixelsSum += pixelsArrS[y][x] ? pixelsArrS[y][x] : 0;
        }
      }
    }
    var averagePixels = pixelsSum / arrNum | 0;
    for (var y = 0; y < pixelsArrB.length; y++) {
      for (var x = 0; x < pixelsArrB[0].length; x++) {
        if (pixelsArrS[y][x] != undefined) {
          if (pixelsArrS[y][x] < averagePixels) {
            blackArrNum++;
            imgStr += "马";
          } else {
            imgStr += "　";
          }
        } else {
          imgStr += "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
          console.log("err");
        }
      }
      imgStr += "\r\n";
    }
    if (blackArrNum > (arrNum / 2)) {
      imgStr.replace(/　/g, "青");
      imgStr.replace(/马/g, "　");
    }
    // fs.writeFileSync("2.txt", imgStr);
    callback(imgStr, pixelsArrS);
  })


  function heightCalculate(smallRate) {
    for (var y = 0; y < imgHeight; y++) {
      var pixelsArrHelfB = [];
      var pixelsArrHelfS = [];
      // 先将每一行的压缩，比如20个字变成5个
      for (var i = 0; i < smallRate; i++) {
        widthCalculate(pixelsArrHelfB, pixelsArrHelfS, y, smallRate);
        y++;
      }
      var len = (pixelsArrHelfB[0].length < pixelsArrHelfS[0].length) ? pixelsArrHelfB[0].length : pixelsArrHelfS[0].length;
      var pixelsArr_B = [];
      var pixelsArr_S = [];
      // 压缩每一列，去除列中的极大极小值，20个变5个
      for (var x = 0; x < len; x++) {
        var biggestOne = 0;
        var smallestOne = 1024;
        for (var i = 0; i < smallRate; i++) {
          if (pixelsArrHelfB[i] && pixelsArrHelfB[i][x] !== undefined) {
            biggestOne = (biggestOne > pixelsArrHelfB[i][x]) ? biggestOne : pixelsArrHelfB[i][x];
            smallestOne = (smallestOne < pixelsArrHelfS[i][x]) ? smallestOne : pixelsArrHelfS[i][x];
          }
        }
        pixelsArr_B.push(biggestOne);
        pixelsArr_S.push(smallestOne);
      }
      pixelsArrB.push(pixelsArr_B);
      pixelsArrS.push(pixelsArr_S);
    }
  }

  function widthCalculate(pixelsArrHelfB, pixelsArrHelfS, y, smallRate) {
    var widthArrB = [];
    var widthArrS = [];
    for (var x = 0; x < imgWidth; x++) {
      var biggestOne = 0;
      var smallestOne = 1024;
      var pixelLoc = y * imgWidth + x;
      for (var i = 0; i < smallRate; i++) {
        biggestOne = (biggestOne > pixelsArr[pixelLoc]) ? biggestOne : pixelsArr[pixelLoc];
        smallestOne = (smallestOne < pixelsArr[pixelLoc]) ? smallestOne : pixelsArr[pixelLoc];
        x++;
      }
      widthArrB.push(biggestOne);
      widthArrS.push(smallestOne);

      // if (biggestOne > BIG_THRESHOLD) {
      //   imgStr += "管";
      // } else if (smallestOne < SMALL_THRESHOLD) {
      //   imgStr += "　"
      // } else {
      //   imgStr += "马";
      // }
    }
    pixelsArrHelfB.push(widthArrB);
    pixelsArrHelfS.push(widthArrS);
  }
}

module.exports.drawLevelStr = function drawLevelStr(srcArr) {
  const CHARACTER_TEMPLATE = ['　', '＇', 'ｉ', '＝', 'Ｘ', 'Ｍ', '五', '市', '双', '蝦', '犇', '龓', '龖'];
  let interval = 256 * 4 / 13 + 1;
  let finalStr = '';
  srcArr.forEach(ele => {
    ele.forEach(ele2 => {
      finalStr += CHARACTER_TEMPLATE[ele2/interval|0] || '▇';//▇■█
    })
    finalStr += '\r\n';
  });
  return finalStr;
}

/*
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" version="1.1">

<path xmlns="http://www.w3.org/2000/svg" d="M250 150 L150 350 L350 350"/>
<path xmlns="http://www.w3.org/2000/svg" d="M2 150 L150 350 L350 350" style="fill:rgba(255,255,255,0);stroke:black;stroke-width:2"/>

</svg>
*/
module.exports.drawLevelSvg = function drawLevelStr(srcArr) {
  let accuracy = 8;
  let interval = 256 * 4 / accuracy + 1;
  let finalSvg = '';
  let _x = 0, _y = 0;
  srcArr.forEach(ele => {
    _x = 0;
    let _path = `M${_x} ${_y}`;
    ele.forEach(ele2 => {
      let lineLevel = (256 * 4 - ele2)/interval|0;
      let isTop = 1;
      let lastX = _x;
      for (var i = 0; i < lineLevel; i++) {
        _x += accuracy / lineLevel | 0;
        _path += ` L${_x} ${isTop*i + _y}`;
        isTop = -isTop;
      }
      _x = lastX + accuracy;
    })
    finalSvg += `\r\n<path xmlns="http://www.w3.org/2000/svg" d="${_path}" style="fill:rgba(255,255,255,0);stroke:black;stroke-width:1"/>`
    _y += accuracy;
  });
  finalSvg = `
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" version="1.1">
    ${finalSvg}
  </svg>
  `;
  return finalSvg;
}